﻿using System.Windows.Forms;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using VisualWip.Core;

namespace VisualWip.TFS2010Providers
{
    public class TfsConnection
    {
        private Project _teamProject;
        private WorkItemStore _workItemStore;

        public TfsConnection()
        {
            ConnectedAs = string.Empty;
        }

        public Project TeamProject
        {
            get
            {
                return _teamProject;
            }
        }

 
        public WorkItemStore WorkItemStore
        {
            get
            {
                return _workItemStore;
            }
        }

        public bool IsConnected { get; private set; }

        public string ConnectedAs { get; private set; }

        public void Connect()
        {
            using (
                var x = new TeamProjectPicker(TeamProjectPickerMode.SingleProject, false, new UICredentialsProvider()))
            {
                if (x.ShowDialog() == DialogResult.OK)
                {
                    TfsTeamProjectCollection projectCollection =
                        TfsTeamProjectCollectionFactory.GetTeamProjectCollection(x.SelectedTeamProjectCollection.Uri);
                    projectCollection.EnsureAuthenticated();

                    ConnectedAs = projectCollection.AuthorizedIdentity.DisplayName;
                    IsConnected = true;

                    _workItemStore = projectCollection.GetService<WorkItemStore>();
                    _teamProject = WorkItemStore.Projects[x.SelectedProjects[0].Name];

                }
            }
        }
    }
}